package com.practices2.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

public class FloatView extends TextView {

	private float x;
	private float y;
	private float xTouchStart;
	private float yTouchStart;

	private WindowManager wm = (WindowManager) this.getContext().getApplicationContext().getSystemService("window");
	private WindowManager.LayoutParams params = new WindowManager.LayoutParams();

	public WindowManager.LayoutParams getLayoutParams() {
		params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
		params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		return params;
	}

	// new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
	// LayoutParams.WRAP_CONTENT);
	// ((MyApplication)
	// this.getContext().getApplicationContext()).getLayoutParams();

	public FloatView(Context context) {
		super(context);
	}

	// View的构造器3中方式，在XML配置必须实现这种
	public FloatView(Context context, AttributeSet set) {
		super(context, set);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		// 获取相对屏幕的坐标，即以屏幕左上角为原点

		x = event.getRawX();
		y = event.getRawY() - 25;// 去掉 系统状态栏的高度

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 获取相对View的坐标，即以此View左上角为原点
			xTouchStart = event.getX();
			xTouchStart = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			updateViewPosition();
			break;
		case MotionEvent.ACTION_UP:
			updateViewPosition();
			xTouchStart = yTouchStart = 0;
			break;
		default:
			break;
		}
		return true;
	}

	private void updateViewPosition() {
		params.x = (int) (x - xTouchStart);
		params.y = (int) (y - yTouchStart);
		wm.updateViewLayout(this, params);
	}

}
